import { Store, Module, ActionContext } from 'vuex'
import ListModule from './list-module'
import ListState from './list-state'
import Ajax from '../../lib/ajax'
import PageResult from '@/store/entities/page-result';
import Company from '../entities/company';
import PermissionTree from '../entities/permissionTree'

interface CompanyState extends ListState<Company> {
    editCompany: Company;

}
class CompanyModule extends ListModule<CompanyState, any, Company>{
    state = {
        totalCount: 0,
        currentPage: 1,
        pageSize: 1000,
        list: new Array<Company>(),
        loading: false,
        editCompany: new Company(),

    }
    actions = {
        async getAll(context: ActionContext<CompanyState, any>, payload: any) {
            context.state.loading = true;
            let reponse = await Ajax.get('/api/services/app/Company/GetPaged', { params: payload.data });
            context.state.loading = false;
            let page = reponse.data.result as PageResult<Company>;

            context.state.totalCount = page.totalCount;

            context.state.list = page.items;
        },
        async getAllTree(context: ActionContext<CompanyState, any>, payload: any) {
            context.state.loading = true;
            let reponse = await Ajax.get('/api/services/app/Company/GetAllTree', { params: payload.data });
            context.state.loading = false;

            reponse.data.result.forEach(el => {
                el._showChildren = true;
            });
            context.state.list = reponse.data.result;

        },
        async create(context: ActionContext<CompanyState, any>, payload: any) {
            return await Ajax.post('/api/services/app/Company/Create', payload.data);
        },
        async update(context: ActionContext<CompanyState, any>, payload: any) {
            return await Ajax.put('/api/services/app/Company/Update', payload.data);
        },
        async delete(context: ActionContext<CompanyState, any>, payload: any) {
            return await Ajax.delete('/api/services/app/Company/Delete?Id=' + payload.data.id);
        },
        async get(context: ActionContext<CompanyState, any>, payload: any) {
            let reponse = await Ajax.get('/api/services/app/Company/GetById?Id=' + payload.id);
            return reponse.data.result as Company;
        },
        async getCompanyTree() {
            let reponse = await Ajax.get('/api/services/app/Company/getCompanyTree');
            return reponse.data.result as PermissionTree;
        },
    };
    mutations = {
        setCurrentPage(state: CompanyState, page: number) {
            state.currentPage = page;
        },
        setPageSize(state: CompanyState, pagesize: number) {
            state.pageSize = pagesize;
        },
        edit(state: CompanyState, company: Company) {
            state.editCompany = company;
        }
    }
}
const companyModule = new CompanyModule();
export default companyModule;